import { login, register, getCurrentUser } from '../../api/user'

// 用户模块
export default {
  namespaced: true,
  state: {
    // 用户信息
    user: JSON.parse(localStorage.getItem('userInfo')) || null,
    // 用户token
    token: localStorage.getItem('token') || null,
    // 是否已登录
    isLoggedIn: !!localStorage.getItem('token')
  },
  
  mutations: {
    // 设置用户信息
    SET_USER(state, user) {
      state.user = user
      localStorage.setItem('userInfo', JSON.stringify(user))
    },
    
    // 设置token
    SET_TOKEN(state, token) {
      state.token = token
      state.isLoggedIn = !!token
      if (token) {
        localStorage.setItem('token', token)
      } else {
        localStorage.removeItem('token')
      }
    },
    
    // 退出登录
    LOGOUT(state) {
      state.user = null
      state.token = null
      state.isLoggedIn = false
      localStorage.removeItem('token')
      localStorage.removeItem('userInfo')
    }
  },
  
  actions: {
    // 登录操作
    async login({ commit, dispatch, rootDispatch }, credentials) {
      try {
        rootDispatch('showLoading')
        commit('CLEAR_ERROR', null, { root: true })
        const response = await login(credentials)
        const { token } = response.data
        commit('SET_TOKEN', token)
        // 获取用户信息
        await dispatch('fetchUserInfo')
        rootDispatch('showSuccess', '登录成功')
        return response
      } catch (error) {
        const errorMsg = error.response?.data?.message || '登录失败'
        rootDispatch('showError', errorMsg)
        throw error
      } finally {
        rootDispatch('hideLoading')
      }
    },
    
    // 获取用户信息
    async fetchUserInfo({ commit }) {
      try {
        const response = await getCurrentUser()
        commit('SET_USER', response.data)
        return response.data
      } catch (error) {
        // 如果获取用户信息失败，可能是token过期，清除token
        commit('LOGOUT')
        throw error
      }
    },
    
    // 退出登录
    logout({ commit, rootDispatch }) {
      commit('LOGOUT')
      rootDispatch('showSuccess', '已退出登录')
    },
    
    // 更新用户信息
    updateUserInfo({ commit, state }, userData) {
      const updatedUser = { ...state.user, ...userData }
      commit('SET_USER', updatedUser)
    },
    
    // 注册操作
    async register({ commit, rootDispatch }, userData) {
      try {
        rootDispatch('showLoading')
        commit('CLEAR_ERROR', null, { root: true })
        const response = await register(userData)
        rootDispatch('showSuccess', '注册成功')
        return response
      } catch (error) {
        const errorMsg = error.response?.data?.message || '注册失败'
        rootDispatch('showError', errorMsg)
        throw error
      } finally {
        rootDispatch('hideLoading')
      }
    }
  },
  
  getters: {
    // 获取用户信息
    userInfo: state => state.user,
    
    // 判断是否登录
    isAuthenticated: state => state.isLoggedIn,
    
    // 判断是否是管理员
    isAdmin: state => {
      // 这里简化处理，实际应该根据用户角色判断
      return state.user?.role === 'ADMIN' || false
    },
    
    // 获取用户昵称或用户名
    userName: state => {
      if (!state.user) return ''
      return state.user.nickname || state.user.username || ''
    },
    
    // 获取用户头像
    userAvatar: state => {
      if (!state.user) return ''
      return state.user.avatar || ''
    }
  }
}